#include <iostream>
#include <algorithm>
using namespace std;
struct S
{
	string name;
	int age;
};
bool cmp_s_by_age(const struct S& s1, const struct S& s2)
{
	return s1.age > s2.age; //按年龄降序
}
bool cmp_s_by_name(const struct S& s1, const struct S& s2)
{
	return s1.name > s2.name;//按名字降序
}
//测试⾃定义⽐较函数
void test1()
{
	struct S s[3] = { {"zhangsan", 20}, {"lisi", 25}, {"wangwu", 18} };
	sort(s, s + 3, cmp_s_by_age);
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		cout << s[i].name << " " << s[i].age << endl;
	}
}
struct CmpByNameLess
{
	bool operator()(const struct S& s1, const struct S& s2)
	{
		return s1.name < s2.name; //按照名字升序
	}
};
struct CmpByAgeGreater
{
	bool operator()(const struct S& s1, const struct S& s2)
	{
		return s1.age > s2.age; //按照年龄降序
	}
};
//测试结构中重载()运算符实现⽐较

void test2()
{
	struct S s[3] = { {"zhangsan", 20}, {"lisi", 25}, {"wangwu", 18} };
	sort(s, s + 3, CmpByNameLess);
	int i = 0;
	for (i = 0; i < 3; i++)
	{
		cout << s[i].name << " " << s[i].age << endl;
	}
}
int main()
{
	test1();
	test2();
	return 0;
}
//#include <iostream>
//#include<algorithm>
//using namespace std;
////仿函数⽅式-仿函数也叫函数对象
////关于仿函数、操作符重载，要深⼊学习C++，竞赛中涉及的较少、也⽐较浅，会⽤就⾏
//struct Cmp
//{
//	bool operator()(int x, int y)
//	{
//		return x > y;//排降序
//	}
//}cmp;
//int main()
//{
//	int arr[] = { 4,5,6,9,7,1,2,8,5,4,2 };
//	int size = sizeof(arr) / sizeof(arr[0]);
//	sort(arr, arr + size, cmp);
//	//将结构体对象作为第三个参数传⼊sort函数中
//	for (int i = 0; i < size; i++)
//	{
//		cout << arr[i] << " ";
//	}
//	cout << endl;
//	return 0;
//}

//#include <iostream>
//#include <algorithm>
//using namespace std;
////
////⾃定义⼀个⽐较函数，这个⽐较函数能够⽐较被排序数据的2个元素⼤⼩
////函数返回bool类型的值
////
//bool compare(int x, int y)
//{
//	return x > y;//排降序
//
//}
//int main()
//{
//	int arr[] = { 4,5,6,9,7,1,2,8,5,4,2 };
//	int size = sizeof(arr) / sizeof(arr[0]);
//	//	将函数名作为第三个参数传⼊sort函数中
//	sort(arr, arr + size, compare);
//	for (int i = 0; i < size; i++)
//	{
//		cout << arr[i] << " ";
//	}
//	cout << endl;
//	return 0;
//}